#include "DragVMToDestination.h"
#include "Collision_lyvm.h"
#include "assert.h"

using namespace std;
DragVMToDestination* DragVMToDestination::DragVM = NULL;

#define move_count 100

DragVMToDestination::DragVMToDestination()
{
}
DragVMToDestination::~DragVMToDestination()
{
}

DragVMToDestination* DragVMToDestination::getInstance(){
	if(DragVM == NULL){
		DragVM = new DragVMToDestination();
	}
	return DragVM;
}
///將要被移動的VM加到我們的移動清單中
void DragVMToDestination::addNeedMoveVM(DIVA_VM *vm, Ogre::Vector3 destination){
	std::vector<move_str*>::iterator move_it;

	for(move_it = record_information.begin();move_it != record_information.end();move_it++){
		if((*move_it)->vm == vm){
			(*move_it)->end = destination;
			Ogre::Vector3 start = vm->getPosition();
			Ogre::Vector3 step = (destination - start)/100;
			(*move_it)->step = step;
			(*move_it)->count = move_count;
			
			return;
		}
	}
	MOVE_STR* ms = (struct move_str *)malloc(sizeof(struct move_str));
	ms->vm = vm;
	ms->end = destination;
	Ogre::Vector3 start = vm->getPosition();
	Ogre::Vector3 step = (destination - start)/100;
	ms->step = step;
	ms->count = move_count;

	record_information.push_back(ms);
}
///做移動度部分
void DragVMToDestination::move(){
	std::vector<move_str*>::iterator move_it;

	for(move_it = record_information.begin();move_it != record_information.end();move_it++){
		if((*move_it)->count != 0){
			Ogre::Vector3 pos = (*move_it)->vm->getPosition() + (*move_it)->step;
			(*move_it)->vm->VMDragged(0,0,pos.x,pos.y,pos.z);
			(*move_it)->count = (*move_it)->count -1;
		}
		else{
			std::vector<DIVA_VM*> cant_move;
			assert(Collision_lyvm::getInstance()->lyvmIsTurnOn() != false);
			cant_move.push_back((*move_it)->vm);
			Collision_lyvm::getInstance()->collision_handling(cant_move,(*move_it)->vm);
			cant_move.clear();
		}
	}
}
///判定是否已經移到我們的目的地
bool DragVMToDestination::move_finish(DIVA_VM* vm){
	std::vector<move_str*>::iterator move_it;

	for(move_it = record_information.begin();move_it != record_information.end();move_it++){
		
		if(((*move_it)->vm == vm) && ((*move_it)->count != 0)){
			return false;
		}
	}
	return true;
}